﻿using DT.GoogleAnalytics.Metro;
using FantasyWereld.Code;
using FantasyWereld.Common;
using FantasyWereld.Data;
using System;
using System.Collections.Generic;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.Search;
using Windows.UI.StartScreen;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

// The Author Detail Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234232

namespace FantasyWereld.Views
{
    /// <summary>
    /// A page that displays details for a single item within a group while allowing gestures to
    /// flip through other items belonging to the same group.
    /// </summary>
    public sealed partial class AuthorDetailPage : FantasyWereld.Common.LayoutAwarePage
    {
        public AuthorDetailPage()
        {
            this.InitializeComponent();
			FadeOpacity.Begin();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            // Allow saved page state to override the initial item to display
            if (pageState != null && pageState.ContainsKey("SelectedItem"))
            {
                navigationParameter = pageState["SelectedItem"];
            }

            // TODO: Create an appropriate data model for your problem domain to replace the sample data
            var item = FWDataSource.GetItem((String)navigationParameter);

            if (item != null)
            {
                // Determine application local link to author
                FWDataSource.AddAuthorInfo(item);

                this.DefaultViewModel["Group"] = item.Group;
                this.DefaultViewModel["Items"] = item.Group.Items;
                this.flipView.SelectedItem = item;

                // Deregister the DataRequested event handler when the handler was already added
                // This can happen when the app restarts itself after settings were changed by the user
                if (_dataRequestHandler != null)
                    DataTransferManager.GetForCurrentView().DataRequested -= _dataRequestHandler;

                // Set the handler to the actual event handler method
                _dataRequestHandler = OnDataRequested;

                // Register for DataRequested event
                DataTransferManager.GetForCurrentView().DataRequested += _dataRequestHandler;
            }
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
            var selectedItem = (FWDataItem)this.flipView.SelectedItem;
            if (selectedItem != null)
            {
                pageState["SelectedItem"] = selectedItem.UniqueId;

                // Deregister the DataRequested event handler
                DataTransferManager.GetForCurrentView().DataRequested -= _dataRequestHandler;

                // Dispose the handler so it can be added when LoadState fires again
                _dataRequestHandler = null;
            }
        }

        private void flipView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            AnalyticsHelper.TrackPageView(pageRoot.ToString());

            var item = (FWDataItem)this.flipView.SelectedItem;

            // Determine application local link to author
            if (item != null)
                FWDataSource.AddAuthorInfo(item);
        }

        void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            var request = args.Request;
            var item = (FWDataItem)this.flipView.SelectedItem;

            if (item != null)
            {
                // Determine application local link to author
                FWDataSource.AddAuthorInfo(item);

                // Fill request with MediaObject Data
                request = Utility.SetMessageRequest(item, request);
            }
        }

        private async void OnBrowseToAuthorButtonClicked(object sender, RoutedEventArgs e)
        {
            var item = (FWDataItem)this.flipView.SelectedItem;
            // Create the URI to launch from a string. 
            var uri = new Uri(item.AuthorLink);

            // Launch the URI. 
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        /// <summary>
        /// Invoked when a user wants to browse to the FantasyWereld website.
        /// </summary>
        /// <param name="sender">Sender parameter is unused</param>
        /// <param name="e">Event data parameters is unused</param>
        private async void OnBrowseToSiteButtonClicked(object sender, RoutedEventArgs e)
        {
            // Create the URI to launch from a string. 
            var uri = new Uri(Constants.WEBSITEBASE);

            // Launch the URI. 
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        /// <summary>
        /// Invoked when a user wants to browse to the FantasyWereld forum.
        /// </summary>
        /// <param name="sender">Sender parameter is unused</param>
        /// <param name="e">Event data parameters is unused</param>
        private async void OnBrowseToForumButtonClicked(object sender, RoutedEventArgs e)
        {
            // Create the URI to launch from a string. 
            var uri = new Uri(Constants.WEBSITE_FORUM);

            // Launch the URI. 
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        /// <summary>
        /// Invoked when a user wants to browse to the FantasyWereld facebook page.
        /// </summary>
        /// <param name="sender">Sender parameter is unused</param>
        /// <param name="e">Event data parameters is unused</param>
        private async void OnBrowseToFacebookButtonClicked(object sender, RoutedEventArgs e)
        {
            // Create the URI to launch from a string. 
            var uri = new Uri(Constants.WEBSITE_FACEBOOK);

            // Launch the URI. 
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        private async void OnPinReviewButtonClicked(object sender, RoutedEventArgs e)
        {
            var item = (FWDataItem)this.flipView.SelectedItem;
            var uniqueId = item.UniqueId.Replace("/", "");
            var uri = await Utility.GetUriLocalImageAsync(item.ImageLink, uniqueId);

            var tile = new SecondaryTile(
                uniqueId,                   // Tile ID
                item.Author,                // Tile display name
                item.UniqueId,              // Activation argument
                uri,                        // Square 150x150 tile logo URI
                TileSize.Default);          // Tilesize must be default

            await tile.RequestCreateAsync();
        }

        private void SearchBoxEventsSuggestionsRequested(object sender, SearchBoxSuggestionsRequestedEventArgs e)
        {
            string queryText = e.QueryText;
            if (!string.IsNullOrEmpty(queryText))
            {
                SearchSuggestionCollection suggestionCollection = e.Request.SearchSuggestionCollection;

                string[] terms = FWDataSource.AllKeywords;

                foreach (var term in terms)
                {
                    if (term.StartsWith(queryText, StringComparison.CurrentCultureIgnoreCase))
                        suggestionCollection.AppendQuerySuggestion(term);
                }
            }
        }

        /// <summary>
        /// Called when query submitted in SearchBox
        /// </summary>
        /// <param name="sender">The Xaml SearchBox</param>
        /// <param name="e">Event when user submits query</param>
        private void SearchBoxEventsQuerySubmitted(object sender, SearchBoxQuerySubmittedEventArgs e)
        {
            var queryText = e.QueryText;
            if (!string.IsNullOrEmpty(queryText))
            {
                // Load books if still necessary
                FWDataSource.LoadBooks();

                // If the Window isn't already using Frame navigation, insert our own Frame
                var previousContent = Window.Current.Content;
                var frame = previousContent as Frame;

                frame.Navigate(typeof(SearchResultsPage), queryText);
                Window.Current.Content = frame;

                // Google Analytics helper
                AnalyticsHelper.Setup();

                // Ensure the current window is active
                Window.Current.Activate();
            }
        }

        private void SearchBox_GotFocus(object sender, RoutedEventArgs e)
        {
            (sender as SearchBox).Width = 250;
        }

        private void SearchBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if ((sender as SearchBox).QueryText == "")
                (sender as SearchBox).Width = 35;
        }

        private void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            var item = (FWBookInfo)e.ClickedItem;

            // Load books if still necessary
            FWDataSource.LoadBooks();

            this.Frame.Navigate(typeof(ItemDetailPage), item.AppLink);
        }

        private async void OnUpdateAuthorButtonClicked(object sender, RoutedEventArgs e)
        {
            // Update author data
            var item = (FWDataItem)this.flipView.SelectedItem;

            // Load books if still necessary
            FWDataSource.LoadBooks();

            if (item != null)
                await FWDataSource.ProcessOneAuthorAsync(item.AuthorUniqueId);
        }
    }
}
